import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getBaseWeatherByAdcode } from '@/api/index.js'

export const WeatherStore = defineStore('weather', () => {
  //定义状态
  const cityWeatherList = ref([])

  //定义方法
  const addCityWeather = (obj) => {
    cityWeatherList.value.push(obj)
  }
  const removeCityWeather = (value) => {
    cityWeatherList.value = cityWeatherList.value.filter((item) => item.adcode != value)
  }

  const getCityWeatherList = async () => {
    //从localStorage中获取数据
    const storedData = localStorage.getItem('cityWeatherList')
    const savedCityWeatherList = JSON.parse(storedData)
    //更新后的城市天气数据
    const updatedCityWeatherList = []
    for (const item of savedCityWeatherList) {
      const latestWeather = await getBaseWeatherByAdcode(item.adcode);
      updatedCityWeatherList.push({
        ...item,
        temperature: latestWeather.lives[0].temperature,
      })
    }
    cityWeatherList.value = updatedCityWeatherList
  }

  watch(
    cityWeatherList,
    () => {
      localStorage.setItem('cityWeatherList', JSON.stringify(cityWeatherList.value))
    },
    { deep: true }
  )

  return {
    cityWeatherList,
    addCityWeather,
    removeCityWeather,
    getCityWeatherList,
  }
})

